//
//  SettingUserNameViewController.m
//  糗事百科
//
//  Created by 奚超明 on 16/5/30.
//  Copyright © 2016年 奚超明. All rights reserved.
//

#import "SettingUserNameViewController.h"
#import "UserModel.h"
#import <CommonCrypto/CommonCrypto.h>
#import "LoginViewController.h"

@interface SettingUserNameViewController () <UITextFieldDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate, UIActionSheetDelegate>
@property (weak, nonatomic) IBOutlet UIButton *finishBtn;
@property (weak, nonatomic) IBOutlet UITextField *userNameTF;
@property (weak, nonatomic) IBOutlet UIButton *iconBtn;

@end

@implementation SettingUserNameViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // 标题
    NSMutableDictionary *attributes = [NSMutableDictionary dictionary];
    attributes[NSForegroundColorAttributeName] = [UIColor darkGrayColor];
    [self.navigationController.navigationBar setTitleTextAttributes:attributes];
    self.navigationItem.title = @"完善资料";
    
    // 返回按钮
    UIButton *backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    backBtn.xcm_size = CGSizeMake(30, 30);
    backBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    backBtn.contentEdgeInsets = UIEdgeInsetsMake(0, -15, 0, 0);
    [backBtn setImage:[UIImage imageNamed:@"back"] forState:UIControlStateNormal];
    [backBtn addTarget:self action:@selector(backAction) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:backBtn];
    
    // 完成按钮圆角
    self.finishBtn.layer.cornerRadius = 5;
    self.finishBtn.layer.masksToBounds = YES;
    
    // 获得的第三方昵称
    self.userNameTF.text = self.userModel.nickname;
    
    // 头像圆角
    self.iconBtn.layer.cornerRadius = self.iconBtn.xcm_width * 0.5;
    self.iconBtn.layer.masksToBounds = YES;
    
    // 如果有第三方头像，则设置
    if (self.userModel.icon) {
        NSData *iconData = [NSData dataWithContentsOfURL:[NSURL URLWithString:self.userModel.icon]];
        [self.iconBtn setBackgroundImage:[UIImage imageWithData:iconData] forState:UIControlStateNormal];
    }
    
    // 加密
}

#pragma mark - 点击更换头像
- (IBAction)changeIconImageView:(UIButton *)sender {
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    // 相机
    UIAlertAction *cameraAction = [UIAlertAction actionWithTitle:@"拍照选取" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
        // 判断是否支持拍照
        if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
            // 创建相册/相机对象
            UIImagePickerController *picker = [[UIImagePickerController alloc] init];
            // 设置是相册
            picker.sourceType = UIImagePickerControllerSourceTypeCamera;
            // 是否可以编辑
            picker.allowsEditing = YES;
            // 设置代理
            picker.delegate = self;
            // 弹出相册
            [self presentViewController:picker animated:YES completion:nil];
        }
    }];
    [alert addAction:cameraAction];
    
    // 相册
    UIAlertAction *photoAction = [UIAlertAction actionWithTitle:@"从相册选取" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        // 判断是否支持相册
        if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {
            // 创建相册/相机对象
            UIImagePickerController *picker = [[UIImagePickerController alloc] init];
            // 设置是相册
            picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
            // 是否可以编辑
            picker.allowsEditing = YES;
            // 设置代理
            picker.delegate = self;
            // 弹出相册
            [self presentViewController:picker animated:YES completion:nil];
        }
    }];
    [alert addAction:photoAction];
    
    // 取消
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    [alert addAction:cancelAction];
    
    [self presentViewController:alert animated:YES completion:nil];
}

#pragma mark - 选择完照片及拍完照时调用的方法
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
{
    // 取到imageView
    [self.iconBtn setBackgroundImage:[info objectForKey:UIImagePickerControllerEditedImage] forState:UIControlStateNormal];
    // 界面消失
    [self dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark - 点击完成
- (IBAction)finishAction:(id)sender {
    // 存储数据
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    [userDefaults setObject:self.userModel.token forKey:@"token"];
    [userDefaults setObject:self.userModel.uid forKey:@"uid"];
    [userDefaults setObject:self.userModel.nickname forKey:@"nickname"];
    [userDefaults setObject:self.userModel.icon forKey:@"icon"];
    [userDefaults setObject:@(self.userModel.platformType) forKey:@"platformType"];
    
    // 记录已经登录
    [userDefaults setObject:@"YES" forKey:@"isLogin"];
    
    // 发送通知
    NSDictionary *userInfo = @{
                               @"name" : self.userModel.nickname,
                               @"icon" : self.userModel.icon
                               };
    NSNotification *note = [NSNotification notificationWithName:@"login" object:nil userInfo:userInfo];
    [[NSNotificationCenter defaultCenter] postNotification:note];
    
    // 回到登录界面之前的界面
    NSArray *subViewControllers = self.navigationController.viewControllers;
    for (UIViewController *subVC in subViewControllers) {
        if ([subVC isKindOfClass:[LoginViewController class]]) {
            [subVC.navigationController dismissViewControllerAnimated:YES completion:nil];
        }
    }
}

#pragma mark - 点击空白收回键盘
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [self.view endEditing:YES];
}

#pragma mark - 点击return收回键盘
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [self.view endEditing:YES];
    return YES;
}

#pragma mark - 返回
- (void)backAction
{
    // 注销登录
    [ShareSDK cancelAuthorize:self.userModel.platformType];
    
    [self.navigationController popViewControllerAnimated:YES];
}

@end
